<template>
	<div class="box" style="background: #fff; overflow: hidden;padding: 10px;">
		<div class="header">
			<!-- 查询 -->
			<input type="text" placeholder="请输入文件名称" v-model="fileName" @input='getInit()'>
		</div>
		<ul class="list">

			<li v-for="(item , index) in fileList" :key="index">
				<van-swipe-cell right-width="100">
					<van-cell-group>
						<div class="centent" @click='goChildren(item)'>
							<p class="p1">
								<!-- 文件夹 -->
								<img v-for="(row,inx) in iconList" :key="inx" :src="row.url" class="iconImage"
									v-if="(row.fileType == item.fileType) && row.suffix.includes(item.suffix)">

								<!-- 文件名称 -->
								<span style="margin-left: 10px;">{{item.fileName}}</span>
							</p>

							<!-- 右边内容展示 -->
							<div class="p2">
								<!-- 文件大小 -->
								<p v-if="item.size && item.fileType != 1">大小：{{item.size}}M</p>

							</div>
						</div>
					</van-cell-group>
					<view slot="right" class="van-swipe-cell__right">
						<!-- 修改文件名称 -->
						<img @click='updateFile(item)'
							src="https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/修改.svg"
							class="iconImage">

						<!-- 删除文件 -->
						<img @click='deleteFile(item)'
							src="https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/删除.svg"
							class="iconImage">

						<!-- 复制文件下载链接 -->
						<img @click='copyUrl(item)'
							src="https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/链接.svg"
							class="iconImage" v-if="item.fileType != 1">
					</view>
				</van-swipe-cell>

			</li>
		</ul>

		<div class="upload">
			<van-uploader @after-read="afterRead" accept='all'>
				<button type="primary">上传文件</button>
			</van-uploader>
		</div>

		<button class="addBtn" @click="addFile">
			<img src="https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/新增.svg"
				style="width: 20px;height: 20px; ">
			</img>
		</button>


		<!-- 新建文件夹 弹出框 -->
		<van-popup :show="isShowNewFolder" @close='isShowNewFolder = false' position="center" round>
			<div style="width: 95vw;height: 200px;position: relative;">
				<van-field :value="saveObj.fileName" autosize type="textarea" placeholder="请输入文件夹名称" :border="false"
					label="文件夹名称" input-align='left' @change="changeInput($event , 'fileName')" />

				<button class="save" @click="save"> 保存 </button>
			</div>
		</van-popup>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				// 当前节点的id
				queryId: '',
				isShowNewFolder: false, //是否显示新建文件夹弹出框
				saveObj: {}, //保存 新建文件夹相关字段

				fileList: [],

				userInfo: {},

				fileName: "", // 通过文件名查询

				iconList: [{
						// 文件夹
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/文件夹.svg",
						fileType: '1',
						suffix: ['文件夹']
					},
					{
						// mp4
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/mp4.svg",
						fileType: '2',
						suffix: ['.mp4', '.mp3' , '.MP4' , '.MP3']
					},
					{
						// pdf
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/pdf.svg",
						fileType: '2',
						suffix: ['.pdf']
					},
					{
						// 表格
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/xlsx.svg",
						fileType: '2',
						suffix: ['.xlsx', '.xls']
					},

					{
						// ppt 
						url: "https://mp-b0e75062-7b5f-440f-98a6-55e57dc35f9a.cdn.bspapp.com/cloudstorage/ppt (1).svg",
						fileType: '2',
						suffix: ['.ppt', '.pptx']
					},

					{
						// 文本
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/PPT.svg",
						fileType: '2',
						suffix: ['.txt']
					},
					{
						// word 文档
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/docx.svg",
						fileType: '2',
						suffix: ['.doc', '.docx']
					},

					{
						// 图片
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/图片.svg",
						fileType: '2',
						suffix: ['.jpg', '.jpeg', '.png', '.gif', '.svg']
					},

					{
						// 网页文件
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/网页设计.svg",
						fileType: '2',
						suffix: ['.html', '.htm', '.xml', '.css', '.js', '.json']
					},

					{
						// 压缩文件
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/压缩包.svg",
						fileType: '2',
						suffix: ['.zip', '.rar', '.7z', '.tar', '.tar', '.bz2']
					},

					{
						// 启动文件
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/exe.svg",
						fileType: '2',
						suffix: ['.exe']
					},

					{
						// md文件
						url: "https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/账单Icon/md.svg",
						fileType: '2',
						suffix: ['.md']
					},
				],

				// 打开附件进度
				progress: 0
			}
		},

		onLoad(option) {
			this.userInfo = uni.getStorageSync('userInfo')
			this.queryId = option.id || ''
			this.getInit()
		},

		methods: {
			// 点击新建文件夹
			async addFile() {
				let result = await this.$axios('overallSituation', {
					state: 'look',
					databaseName: "folder",
					queryId: this.queryId ? this.queryId : 'maximum',
					fileName: '新建文件夹',
				}, false)

				this.saveObj = {
					fileName: result.data.length == 0 ? '新建文件夹' : '新建文件夹(' + (result.data.length + 1) + ')',
					fileUrl: '',
					fileType: '1', //1 表示文件夹 2 表示文件
					suffix: '文件夹',
					createTime: '',
					queryId: this.queryId ? this.queryId : 'maximum',
					size: ''
				}

				this.saveObj.createTime = this.processingTime() //获取当前时间

				this.isShowNewFolder = true
			},

			// 获取文件列表
			async getInit() {
				// 定义查询条件
				let serch = {
					queryId: this.queryId ? this.queryId : 'maximum',
					fileName: this.fileName
				}

				let result = await this.$axios('overallSituation', {
					state: 'look',
					databaseName: "folder",
					...serch
				}, true)

				if (result.code == 200) {
					this.fileList = result.data
				}
			},

			// 新建文件夹 保存
			async save() {
				if (!this.saveObj.fileName) return

				let result = await this.$axios('overallSituation', {
					state: this.saveObj._id ? 'update' : 'add',
					databaseName: "folder",
					...this.saveObj
				}, true)

				if (result.code == 200) {

					uni.showToast({
						title: '操作成功',
						icon: "none",
						duration: 2000
					})

					this.getInit()

					this.isShowNewFolder = false
				} else {
					uni.showToast({
						title: '操作失败',
						icon: "none",
						duration: 2000
					})

					this.isShowNewFolder = false
				}

			},

			// 修改 文件名称
			updateFile(item) {
				this.saveObj = item
				this.isShowNewFolder = true
			},

			// 复制下载链接
			copyUrl(item) {
				uni.setClipboardData({
					data: item.fileUrl, //要被复制的内容
					success: () => { //复制成功的回调函数
						uni.showToast({ //提示
							title: '下载地址已复制到剪切板',
							icon: "none"
						})
					}
				});
			},

			// 删除文件夹
			async deleteFile(item) {
				uni.showModal({
					title: '提示',
					content: '您确定删除这个文件吗？',
					confirmText: "确定", //这块是确定按钮的文字
					cancelText: "取消", //这块是取消的文字
					success: (res) => {
						if (res.confirm) {
							this.del(item)
						}
					},
				})
			},

			async del(item) {
				try {
					// 先删除当前点击元素
					await this.$axios('overallSituation', {
						state: 'delete',
						databaseName: "folder",
						_id: item._id
					}, false);

					// 查询当前 id 绑定的所有子集
					const result = await this.$axios('overallSituation', {
						state: 'look',
						databaseName: "folder",
						queryId: item._id
					}, false);

					if (result.code === 200 && result.data.length !== 0) {
						// 使用 Promise.all 来确保所有子项都被删除
						await Promise.all(result.data.map(async row => {
							await this.del(row);
						}));
					}

					// 所有操作完成后的逻辑
					uni.showToast({
						title: "操作成功",
						icon: "none",
						duration: 2000
					})
					this.getInit()
					// 这里可以添加其他逻辑，比如更新 UI 等
				} catch (error) {
					uni.showToast({
						title: "操作失败",
						icon: "none",
						duration: 2000
					})
				}
			},

			// 文件上传成功 / 处理文件上传的逻辑
			async afterRead(e) {
				this.fileObj = e.detail.file

				// 弹出输入文件名称的弹框
				uni.showLoading({
					title: `上传中(${(this.fileObj.size / 1024 / 1024).toFixed(2)}M)...`,
				})

				this.saveObj = {
					fileName: this.fileObj.name,
					fileUrl: this.fileObj.url,
					fileType: '2', //1 表示文件夹 2 表示文件
					createTime: '',
					suffix: '',
					queryId: this.queryId ? this.queryId : 'maximum',
					size: (this.fileObj.size / 1024 / 1024).toFixed(2) //文件大小
				}

				// 保存文件后缀
				this.saveObj.suffix = this.getFileExtension(this.saveObj.fileName)

				this.saveObj.createTime = this.processingTime() //获取当前时间

				// 将地址转为线上的
				let imageRes = await uniCloud.uploadFile({
					filePath: this.saveObj.fileUrl,
					cloudPath: this.saveObj.fileName,
					header: {
						"Content-Type": "multipart/form-data"
					},
				})


				this.saveObj.fileUrl = imageRes.fileID

				// 存储
				let result = await this.$axios('overallSituation', {
					state: 'add',
					databaseName: "folder",
					...this.saveObj
				}, false)

				uni.hideLoading()

				if (result.code == 200) {

					uni.showToast({
						title: '操作成功',
						icon: "none",
						duration: 2000
					})

					this.getInit()

					this.isShowNewFolder = false
				} else {
					uni.showToast({
						title: '操作失败',
						icon: "none",
						duration: 2000
					})

					this.isShowNewFolder = false
				}


			},

			// 输入框发生变化
			changeInput(e, str) {
				this.saveObj[str] = e.detail
			},

			// 前往子集节点
			goChildren(item) {
				if (item.fileType == 1) {
					this.$router(`/subPackages2/pages/folder/index?id=${item._id}`)
				} else {
					uni.showLoading({
						title: "正在打开",
					})

					let temporaryUrl = {};
					// 直接通过 item 身上的临时地址打开

					if (Array.isArray(item.temporaryUserData) && item.temporaryUserData.length != 0) {
						item.temporaryUserData.forEach(row => {
							if (row.visitUser == this.userInfo._id) {
								temporaryUrl = row
							}
						})
					}
					
					if (temporaryUrl.temporaryUrl) {
						uni.openDocument({
							filePath: temporaryUrl.temporaryUrl,
							showMenu: true, //允许分享
							success: (res) => {
								uni.hideLoading()
							},
							fail: (error) => {
								console.log("打开失败,下载并且打开");
								// 打开失败 通过下载并且打开
								this.downloadFile(item)
							}
						})
					} else {
						// 下载文件并且打开
						this.downloadFile(item)
					}


				}
			},

			// 下载文件并且打开
			downloadFile(item) {
				let downloadFile = uni.downloadFile({
					url: item.fileUrl,
					success: res => {
						console.log(res.tempFilePath, 'res.tempFilePath');
						if (res.statusCode == '200') {

							let obj = item
							if (Array.isArray(obj.temporaryUserData) && obj.temporaryUserData.length != 0) {
								let flag = true
								obj.temporaryUserData.forEach(item => {
									if (item.visitUser == this.userInfo._id) {
										item.temporaryUrl = res.tempFilePath
										flag = false
									}
								})
								
								if(flag){
									obj.temporaryUserData.push({
										temporaryUrl: res.tempFilePath, //浏览的临时地址
										// 记录用户id
										visitUser: this.userInfo._id
									})
								}
								
							} else {
								obj.temporaryUserData = []
								obj.temporaryUserData.push({
									temporaryUrl: res.tempFilePath, //浏览的临时地址
									// 记录用户id
									visitUser: this.userInfo._id
								})
							}

							// 存储这一份临时地址
							this.$axios('overallSituation', {
								state: 'update',
								databaseName: "folder",
								...obj
							}, false)

							uni.hideLoading()
							uni.openDocument({
								filePath: res.tempFilePath,
								showMenu: true, //允许分享
							})
						}
					}
				})

				downloadFile.onProgressUpdate(res => {
					this.progress = res.progress
					uni.showLoading({
						title: "正在打开" + this.progress + '%',
					})
				})
			},


			// 获取当前时间
			processingTime() {
				let date = new Date();

				// 处理年月日
				let year = date.getFullYear().toString();
				let month = (date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1);
				let day = date.getDate() > 10 ? date.getDate() : '0' + date.getDate();

				// 处理时分秒
				let h = date.getHours() > 10 ? date.getHours() : '0' + date.getHours();
				let m = date.getMinutes() > 10 ? date.getMinutes() : '0' + date.getMinutes();
				let s = date.getSeconds() > 10 ? date.getSeconds() : '0' + date.getSeconds();

				return year + '-' + month + '-' + day + " " + h + ":" + m + ':' + s
			},

			// 截取文件后缀
			getFileExtension(fileName) {
				// 查找最后一个 '.' 的位置
				const dotIndex = fileName.lastIndexOf('.');

				// 如果没有找到 '.' 或者它在字符串的开始位置，则返回空字符串
				if (dotIndex === -1 || dotIndex === 0) {
					return '';
				}

				// 从 '.' 位置到字符串结束的部分就是扩展名
				return fileName.substring(dotIndex);
			},
		}
	}
</script>

<style scoped>
	.header {
		width: 100%;
		height: 7%;
		display: flex;
		align-items: center;
		justify-content: center;
		border-bottom: 1px solid #f1f1f1;
	}

	.header input {
		width: 95%;
		height: 35px;
		color: #333;
		padding: 0 10px;
		background-color: #f1f1f1;
		box-sizing: border-box;
		border-radius: 10px;
		font-size: 12px;
	}

	.list {
		width: 100%;
		height: 84%;
		overflow-y: auto;
	}

	.list li {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px;
		box-sizing: border-box;
		font-size: 14px;
		font-weight: 700;
		border-bottom: 1px solid #999;
	}

	.list li .centent {
		width: 90vw;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.list li .p1 {
		width: 60%;
		display: flex;
		align-items: center;

	}

	.list li .p1 span {
		width: 90%;
		display: inline-block;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}

	.list li .p2 {
		width: 40%;
		text-align: right;
		font-size: 10px;
		font-weight: 400;
		color: #999;
	}

	.list li .iconImage {
		width: 16px;
		height: 16px;
	}

	.addBtn {
		width: 50px;
		height: 50px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		font-weight: 700;
		border-radius: 50%;
		background: #1BA035;
		color: #fff;
		position: absolute;
		bottom: 80px;
		right: 10px;
	}

	.upload {
		width: 100%;
		height: 8%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.upload button {
		width: 95vw;
		height: 35px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12px;
	}

	.save {
		width: 95%;
		height: 35px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12px;
		font-weight: 700;
		color: #fff;
		background: #1BA035;
		margin-top: 60px;
		position: absolute;
		bottom: 10px;
		left: 50%;
		transform: translateX(-50%);
	}

	.van-swipe-cell__right {
		width: 100px;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: space-around;
		border-left: 1px solid #999;
		margin-left: 5px;
	}

	>>>.van-hairline--top-bottom:after {
		border: none !important;
	}
</style>